import React, { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { KeepAlive, AliveScope } from "react-activation";
import { CloseOutlined } from "@ant-design/icons";
import {
  sortableContainer,
  sortableElement,
  arrayMove,
} from "react-sortable-hoc";
import "./KeepAliveTabs.scss";

const normalizePath = (p) => p.replace(/\/+$/, "").toLowerCase();

const findTitleByPath = (routes = [], path) => {
  const normalizedPath = normalizePath(path);
  for (const route of routes) {
    if (normalizePath(route.path) === normalizedPath) {
      return route.meta?.title || path;
    }
    if (route.children) {
      const childTitle = findTitleByPath(route.children, path);
      if (childTitle) return childTitle;
    }
  }
  return null; // 🚨 注意这里不要返回 path 了
};

// 单个标签
const SortableItem = sortableElement(
  ({ tab, removeTab, activeKey, setActiveKey, navigate }) => (
    <div
      className={`tab-label ${activeKey === tab.key ? "active" : ""}`}
      onClick={() => {
        setActiveKey(tab.key);
        navigate(tab.key);
      }}
    >
      <span className="tab-text">{tab.label}</span>
      {tab.closable && (
        <CloseOutlined
          className="tab-close-icon"
          onClick={(e) => {
            e.stopPropagation();
            removeTab(tab.key);
          }}
        />
      )}
    </div>
  )
);

// 拖拽容器
const SortableTabsContainer = sortableContainer(
  ({ tabs, removeTab, activeKey, setActiveKey, navigate }) => {
    return (
      <div className="tabs-container">
        {tabs.map((tab, index) => (
          <SortableItem
            key={`item-${tab.key}`}
            index={index}
            tab={tab}
            removeTab={removeTab}
            activeKey={activeKey}
            setActiveKey={setActiveKey}
            navigate={navigate}
          />
        ))}
      </div>
    );
  }
);

const KeepAliveTabs = ({ children, routes = [] }) => {
  const navigate = useNavigate();
  const location = useLocation();

  const [tabs, setTabs] = useState([
    { label: "首页", key: "/home", closable: true },
  ]);
  const [activeKey, setActiveKey] = useState(location.pathname);

  useEffect(() => {
    if (!routes.length) return;
    const currentPath = location.pathname;
    const exists = tabs.find((tab) => tab.key === currentPath);
    if (!exists) {
      const title = findTitleByPath(routes, currentPath) || currentPath;
      setTabs([...tabs, { label: title, key: currentPath, closable: true }]);
    }
    setActiveKey(currentPath);
  }, [location, routes]);

  const removeTab = (targetKey) => {
    const newTabs = tabs.filter((tab) => tab.key !== targetKey);
    if (newTabs.length === 0) return;
    setTabs(newTabs);
    if (activeKey === targetKey && newTabs.length) {
      navigate(newTabs[newTabs.length - 1].key);
      setActiveKey(newTabs[newTabs.length - 1].key);
    }
  };

  const onSortEnd = ({ oldIndex, newIndex }) => {
    setTabs(arrayMove(tabs, oldIndex, newIndex));
  };

  return (
    <AliveScope>
      <SortableTabsContainer
        axis="x"
        tabs={tabs}
        removeTab={removeTab}
        activeKey={activeKey}
        setActiveKey={setActiveKey}
        navigate={navigate}
        onSortEnd={onSortEnd}
        distance={5}
      />
      <KeepAlive id={activeKey} name={activeKey}>
        {children}
      </KeepAlive>
    </AliveScope>
  );
};

export default KeepAliveTabs;
